// 多表头配置组件

import crudHeaderProperties from '@/api/erp/headerProperties'
import headConfig from '@/headConfig'
import { JScan } from '@/utils/jScan'
import Vue from 'vue'
import { get as getDictDetail } from '@/api/system/dictDetail'
import { getHeaderProperties } from '../api/erp/headerProperties'
import rightClickMenu from '@/components/rightClickMenu/rightClickMenu'
import jTableColumnConfig from '@/components/jTableColumnConfig/jTableColumnConfig'
import { debounce } from '../utils/auth'


  export const manyTableMixin = {
  components: { rightClickMenu, jTableColumnConfig },
  data() {
    return {
      //打印参数
      showPdf: false,
      pdfSrc: '',
      // 绑定值
      manyTableOption: {
        example: this,
        head: '',
        // 是否开启自定义右键
        showMenu: true
      },
      pathObj: {
        report: [1, 2],
        sale: [1, 1]
      },
      // 当前表表格header
      currentHeader: [],
      // 获取表头请求
      headerInfo: {},
      // 显示右键配置
      rightClickMenuConfig: {
        // 显示菜单
        showRightClickMenu: false,
        // 坐标
        location: {
          x: 0,
          y: 0
        },
        // 菜单选项
        menulists: []
      },
      // 初始右键事件
      initialRightEvent: [
        {
          fnHandler: 'tableConfig', // 绑定事件
          icoName: 'el-icon-setting', // icon图标
          btnName: '表格设置' // 菜单名称
        }
      ],
      // 右键扩展事件
      extendRightEvent: {},
      rowIndex: -1,
      header: [],
      tableConfigShow: false,
      contextMenuData: {
        menuName: 'table',
        axis: {
          x: null,
          y: null
        },
        // 菜单选项
        menulists: [
          {
            fnHandler: 'tableConfig', // 绑定事件
            icoName: 'el-icon-setting', // icon图标
            btnName: '表格设置' // 菜单名称
          },
          {
            fnHandler: 'copy', // 绑定事件
            icoName: 'el-icon-edit', // icon图标
            btnName: '复制' // 菜单名称
          }

        ]
      },
      //是否请求表头  作用于表头固定
      whetherGetHeader: true
    }
  },
  created() {
    // 初始化查询参数
    this.headerInfo = {
      code: this.$options.name,
      userId: this.$store.state.user.user.userId,
      path: this.getPath(this.$route.path)
    }
    // 设置表头
    this.getHeader()
    this.crud.headerInfo = this.headerInfo;
    // this.initHeader()
  },
  changeColWidth(nw, ow, col, evt) {
    const list = this.currentHeader
    list.find(item=>item.showName  === col.label).width = nw
    this.saveHead()
  },
  updated() {
    this.$nextTick(() => {
      this.$refs.table.doLayout();
    });
  },
  methods: {
    // 返回表格配置对象
    setHeadName(name) {
      const obj = Object.assign({}, this.manyTableOption)
      obj.example = this.manyTableOption.example
      obj.head = name
      return obj
    },
    changeColWidth(nw, ow, col, evt) {
      const list = this.header
      list.find(item => item.showName === col.label).width = nw
      this.saveHead()
    },
    /**
     * 解决与tablemixin重名
     * @param nw
     * @param ow
     * @param col
     * @param evt
     */
    changeColWidthMany(nw, ow, col, evt) {
      const list = this.currentHeader
      list.find(item=>item.showName  === col.label).width = nw
      this.saveHead()
    },
    // 初始化表头
    initHeader() {
      this.header = headConfig[this.headerInfo.code]
      this.saveHead()
    },
    // 获取表头
    getHeader() {
      const data = {
        modelName: this.headerInfo.code,
        url: this.headerInfo.path,
        userId: this.$store.state.user.user.userId
      }
      getHeaderProperties(data).then(res => {
        if (res.data.header.content === '[]' || !res.data.header.content) {
          if (headConfig.headerList.includes(this.headerInfo.code)) { this.header = headConfig[this.headerInfo.code] }
        }else {
          this.header = JSON.parse(res.data.header.content)
        }
      }).catch(err => {
        throw new Error(err)
      })
    },
    // 解析path
    getPath(url) {
      const list = url.split('/')
      if(Object.keys(this.pathObj).includes(list[1])){
        list.splice(this.pathObj[list[1]][0], this.pathObj[list[1]][1])
        return 'api' + list.join('/')
      }
      const ending = list.pop()
      if (ending.includes('?') || ending.includes('copy') || !isNaN(Number(ending))) {
        return 'api' + list.join('/')
      } else {
        return 'api' + url
      }
    },
    // 保存表头
    saveHead:debounce(function(){
        const data = Object.assign({}, this.headerInfo, { content: JSON.stringify(this.header) })
        data.name = data.code
        crudHeaderProperties.add(data)
        this.tableConfigShow = false
    }),
    tableConfig() {
      this.tableConfigShow = true
    },
    sortTab(row, before) {
      if (row.column.order) {
        this.query.sort = `${before || 't'}.${row.column.property} ${row.column.order === 'ascending' ? 'asc' : 'desc'}`
        // this.sort[row.column.property] = row.column.order === 'ascending'?'asc':'desc'
      } else {
        try {
          this.query.sort = null
          // Reflect.deleteProperty(this.sort,row.column.property)
        } catch (e) {
          console.err(e)
        }
      }
      this.crud.toQuery()
    },
    showMenu() {
      if (event.target.tagName === 'INPUT' || event.target.tagName === 'TEXTAREA') {
        return
      }
      event.preventDefault()
      var x = event.clientX
      var y = event.clientY
      // Get the current location
      this.contextMenuData.axis = {
        x, y
      }
    },
    columnLabel(obj) {
      if (obj.showName) {
        return obj.showName
      }
      obj.showName = obj.label
      return obj.showName
    },
    getDict(str) {
      try {
        return eval(str)
      } catch (e) {
        const w = str.split('.')
        const n = str.split('.')[3].split('[')[0]
        if (!n) {
          return
        }
        this.queryDict(n).then(r => {
          return eval(w.join('.'))
        })
      }
    },
    async queryDict(n) {
      Vue.set(this.dict.dict, n, {})
      Vue.set(this.dict.label, n, {})
      Vue.set(this.dict, n, [])
      const that = this
      await getDictDetail(n).then(data => {
        const _data = data.data.content
        this.dict[n].splice(0, 0, ..._data)
        _data.forEach(d => {
          if (parseInt(d.value).toString() != 'NaN') {
            d.value = parseInt(d.value)
          }
          Vue.set(that.dict.dict[n], d.value, d)
          Vue.set(that.dict.label[n], d.value, d.label)
        })
      })
    }

  }
}
